<template>
	<view :id="`avatar_${canvasId}`">
		<image :src="imgUrl" :style="{width:`${width}rpx`,height:`${width}rpx`}"></image>
		<!-- <u-image :src="imgUrl" :width="`${width}rpx`" :height="`${width}rpx`"></u-image> -->

		<canvas class="canvas" type="2d" :id="canvasId" :canvasId="canvasId"
			:style="{width:`${width}px`,height:`${width}px`}"></canvas>
	</view>
</template>

<script>
	import createAvatar from '@/uni_modules/ch-avatar/js_sdk/index.js'
	export default {
		props: {
			canvasId: {
				type: String,
				default: Date.now().toString()
			},
			data: {
				type: Array,
				default: () => []
			},
			width: {
				type: Number,
				default: 120
			},
			bgColor: {
				type: String,
				default: '#cecece'
			},
			gutter: {
				type: Number,
				default: 4
			},
			margin: {
				type: Number,
				default: 4
			},
		},
		data() {
			return {
				imgUrl: '',
			}
		},
		watch: {
			data: {
				async handler(nVal) {
					if (!nVal) {
						return
					}
					this.imgUrl = await this.createAvatar()
				},
				deep: true,
				immediate: true
			}
		},
		methods: {
			async createAvatar() {
				let res = await createAvatar({
					canvasId: this.canvasId,
					data: this.data,
					width: this.width,
					bgColor: this.bgColor,
					gutter: this.gutter,
					margin: this.margin,
				}, this)
				return res
			}
		}
	}
</script>

<style lang="scss">
	.canvas {
		position: fixed;
		top: -200vh;
		right: -200vw;
	}
</style>